﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace YoUI.Core
{

    /// <summary>
    /// 音频管理器
    /// </summary>
    public class YoAudioMgr : MonoBehaviour
    {

        public static YoAudioMgr _;

        // UI中播放背景音乐
        private AudioSource bgm;
        // UI中播放其他音效
        private AudioSource ogm;

        private Dictionary<string, AudioClip> _CacheAudio;

        public void Awake()
        {
            _ = this;

            _CacheAudio = new Dictionary<string, AudioClip>();

            AudioSource[] ass = GetComponents<AudioSource>();
            bgm = ass[0];
            ogm = ass[1];
        }


        /// <summary>
        /// 播放背景音乐
        /// </summary>
        /// <param name="name">名称</param>
        /// <param name="loop">是否循环</param>
        public void PlayBGM(string name, bool loop = true)
        {
            AudioClip clip = LoadAudio(name);
            bgm.clip = clip;
            bgm.loop = loop;
            bgm.Play();
        }

        public void Play(string name)
        {
            AudioClip clip = LoadAudio(name);
            Play(clip);
        }

        public void Play(AudioClip clip)
        {
            AudioSource.PlayClipAtPoint(clip, Vector3.zero);
        }

        public void AddAudioClip(AudioClip clip)
        {
            Debug.Log(clip);
        }

        private AudioClip LoadAudio(string name)
        {
            // 判断缓存中是否有音效
            AudioClip clip;
            if (!_CacheAudio.TryGetValue(name, out clip))
            {
                string path = null;
                if (!YoConfigMgr._._DicAudioCFG.TryGetValue(name, out path))
                {
                    return null;
                }

                clip = Resources.Load<AudioClip>(YoSysDefine.Yo_ROOT + "/" + path);

                if (clip != null)
                {
                    _CacheAudio.Add(name, clip);
                }
            }
            return clip;
        }
    }
}

